package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocket webSocket;

    @Value("${sky.shop.address}")
    private String shop;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1 添加订单表
        Orders orders = new Orders();
        //拷贝数据
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //补充数据
        orders.setNumber(UUID.randomUUID().toString().replace("-","")); //订单号
        orders.setStatus(Orders.PENDING_PAYMENT); //订单状态
        orders.setUserId(BaseContext.getCurrentId()); //用户ID
        orders.setOrderTime(LocalDateTime.now()); //下单时间
        //orders.setCheckoutTime(); //结账时间
        orders.setPayStatus(Orders.UN_PAID); //支付状态
        //获取User信息
        User user = userMapper.selectById(BaseContext.getCurrentId());

        //获取地址信息
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        //判断地址是否为空
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        orders.setAddress(addressBook.getProvinceName()
                         + addressBook.getCityName()
                         + addressBook.getDistrictName()
                         + addressBook.getDetail()); //地址
        //---------------------------------------------------------------------
        //判断位置距离是否能够配送,使用百度地图检测
        checkOutOfRange(orders.getAddress());
        //---------------------------------------------------------------------
        orders.setPhone(addressBook.getPhone()); //手机号
        orders.setUserName(user.getName()); //用户名称
        orders.setConsignee(addressBook.getConsignee()); //收货人

        //添加订单
        ordersMapper.insert(orders);

        //2 添加订单详情表
        //查询购物车信息
        List<ShoppingCart> list = shoppingCartMapper.selectShoppingCart(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        list.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).forEach(orderDetail -> orderDetailMapper.insert(orderDetail));


        return new OrderSubmitVO(orders.getId(),orders.getNumber(),orders.getAmount(),orders.getOrderTime());
    }

    /**
     * 订单支付--真实的
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception{
//        //创建客户端
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        //创建Post请求
//        HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"); //微信支付请求路径
        //创建数据体
        Map<String,String> map = new HashMap<>();
        map.put("appid","wxd678efh567hg6787"); //应用ID
        map.put("mchid","1230000109"); //直连商户号
        map.put("description","真皮网咖"); //商品描述
        map.put("out_trade_no","1217752501201407033233368018"); //商户订单号
        map.put("notify_url","https://6ffcf133.r2.cpolar.cn/user/order/paySuccess"); //通知地址
        map.put("amount","{'total':0.01,'currency':'CNY'}"); //订单金额信息
        map.put("payer","{'openid':'o4GgauInH_RCEdvrrNGrntXDuXXX'}"); //支付者信息

        String response = HttpClientUtil.doPost4Json("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi", map);
//        //创建字符型数据体
//        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map));
//        //添加post请求体
//        post.setEntity(stringEntity);
//        //发送请求
//        CloseableHttpResponse response = httpClient.execute(post);
//        //获取请求体
//        HttpEntity entity = response.getEntity();
//        //转为字符串
//        String string = EntityUtils.toString(entity);

        //创建OrderPaymentVO,并将response中的参数设置进去
        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();

        return orderPaymentVO;
    }


    /**
     * 订单支付 -虚假的支付成功
     * @param ordersPaymentDTO
     * @return
     * @throws Exception
     */
    @Override
    public void update(OrdersPaymentDTO ordersPaymentDTO) {
        //通过OrderNumber查找订单
        Orders orders = ordersMapper.selectByorderNumber(ordersPaymentDTO.getOrderNumber());
        //更改订单信息--支付成功
        orders.setPayMethod(ordersPaymentDTO.getPayMethod()); //支付方式
        orders.setStatus(Orders.TO_BE_CONFIRMED); //订单状态 ,待接单
        orders.setCheckoutTime(LocalDateTime.now()); //结账时间
        orders.setPayStatus(Orders.PAID); //支付状态,已支付
        //修改订单表信息
        ordersMapper.update(orders);

        //商家来单提醒
        Map<String,Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号: "+ orders.getNumber());
        //发送信息给商家接单提醒
        webSocket.sendAllServer(JSON.toJSONString(map));

        //删除购物车--付款成功及时删除
        shoppingCartMapper.delete(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectOld(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //查询订单
        Page<OrderVO> vo = ordersMapper.selectOld(BaseContext.getCurrentId(),ordersPageQueryDTO.getStatus(),null);
        for (OrderVO orderVO : vo) {
            //查询订单详情
            List<OrderDetail> list = orderDetailMapper.select(orderVO.getId());
            orderVO.setOrderDetailList(list);
        }

        return new PageResult(vo.getTotal(),vo.getResult());
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
        public OrderVO selectDetail(Long id) {
        Page<OrderVO> page = ordersMapper.selectOld(null,null,id);
        OrderVO vo = page.get(0);
        List<OrderDetail> list = orderDetailMapper.select(id);
        vo.setOrderDetailList(list);
        return vo;
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    @Override
    public void cancel(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        //判断订单状态
        //查询订单
        OrderVO vo = ordersMapper.selectOld(null, null, id).get(0);
        //如果是未付款状态 pay_status = 0 , 直接取消,修改status为6
        if (vo.getPayStatus() == 0){
            orders.setStatus(Orders.CANCELLED);
        }
        //如果是已付款状态.pay_status = 1 , 设置pay_status=2,status=7
        if (vo.getPayStatus() == 1){
            orders.setPayStatus(Orders.REFUND);
            orders.setStatus(Orders.CANCELLED);
            //TODO::再通过微信服务端退款操作
        }
        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     * @return
     */
    @Override
    public void repetition(Long id) {
        //再来一单---将此订单的菜品/套餐再次加入购物车
        List<OrderDetail> list = orderDetailMapper.select(id);
        list.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).forEach(shoppingCart -> shoppingCartMapper.insertShoppingCart(shoppingCart));
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = ordersMapper.selectByPage(ordersPageQueryDTO);
        return new PageResult(orders.getTotal(),orders.getResult());
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO count() {
        Integer toBeConfirmed = ordersMapper.selectCount(Orders.TO_BE_CONFIRMED,null);//待接单数量
        Integer confirmed = ordersMapper.selectCount(Orders.CONFIRMED,null); //待派送数量
        Integer deliveryInProgress = ordersMapper.selectCount(Orders.DELIVERY_IN_PROGRESS,null);//派送中数量
        if (toBeConfirmed == null){
            toBeConfirmed = 0;
        }
        if (confirmed == null){
            confirmed = 0;
        }
        if (deliveryInProgress == null){
            deliveryInProgress = 0;
        }
        return new OrderStatisticsVO(toBeConfirmed,confirmed,deliveryInProgress);
    }

    /**
     * 接单
     * @param orders
     * @return
     */
    @Override
    public void confirm(Orders orders) {
        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //TODO::需要判断,如果payStatus == 1,则为已付款,需要退款给用户
        ordersMapper.update(Orders.builder()
                    .id(ordersRejectionDTO.getId())
                    .rejectionReason(ordersRejectionDTO.getRejectionReason())
                    .status(Orders.CANCELLED)
                    .payStatus(Orders.REFUND)
                    .build());
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //TODO::需要判断,如果payStatus == 1,则为已付款,需要退款给用户
        ordersMapper.update(Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .build());
    }

    /**
     * 派送订单
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        ordersMapper.update(Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build());
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        ordersMapper.update(Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build());
    }

    /**
     * 催单
     * @param id
     * @return
     */
    @Override
    public void reminder(Long id) {
        OrderVO vo = ordersMapper.selectOld(null, null, id).get(0);
        Map<String,Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号: "+ vo.getNumber());
        //用户催单提醒
        webSocket.sendAllServer(JSON.toJSONString(map));

    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shop);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

}
